package com.uk.reports;

import static net.sf.dynamicreports.report.builder.DynamicReports.cmp;


import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.builder.DynamicReports;
import net.sf.dynamicreports.report.builder.column.Columns;
import net.sf.dynamicreports.report.builder.component.ComponentBuilder;
import net.sf.dynamicreports.report.builder.component.Components;
import net.sf.dynamicreports.report.builder.component.HorizontalListBuilder;
import net.sf.dynamicreports.report.builder.datatype.BigDecimalType;
import net.sf.dynamicreports.report.builder.datatype.DataTypes;
import net.sf.dynamicreports.report.builder.datatype.DateType;
import net.sf.dynamicreports.report.builder.style.FontBuilder;
import net.sf.dynamicreports.report.builder.style.StyleBuilder;
import net.sf.dynamicreports.report.builder.style.StyleBuilders;
import net.sf.dynamicreports.report.builder.style.Styles;
import net.sf.dynamicreports.report.constant.HorizontalAlignment;
import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.dynamicreports.report.builder.FieldBuilder;
import com.uk.FaturaUKApplication;
import com.uk.data.ejbs.IFaturaBean;

import com.uk.data.entities.Fatura;
import com.uk.data.entities.Kontrata;
import com.uk.data.entities.ParamsEnum;
import com.uk.data.entities.Tarifa;
import com.vaadin.terminal.StreamResource;
import com.vaadin.ui.Embedded;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import static net.sf.dynamicreports.report.builder.DynamicReports.*;

public class Reports {

	
	private static void addAttribute(HorizontalListBuilder list, String label, FieldBuilder<?> value) {  
        if (value != null) {  
            list.add(cmp.text(label + ":").setFixedColumns(8).setStyle(Templates.boldStyle), cmp.text(value)).newRow();  
        } 
	}
       
	public static JasperReportBuilder buildDebitorReport(List<Kontrata> debitorList){
		final JasperReportBuilder report = DynamicReports.report();
		report.setTemplate(Templates.reportTemplate);
		final ComponentBuilder<?, ?> logo = cmp.image(Templates.class.getResource("logo.jpg")).setFixedDimension(200, 80);
		final ComponentBuilder<?, ?> title2 = cmp.text(FaturaUKApplication.PARAMS.get(ParamsEnum.FATURA_REPORT_TITLE_2.name()));
		final ComponentBuilder<?, ?> title1 = cmp.text(FaturaUKApplication.PARAMS.get(ParamsEnum.FATURA_REPORT_TITLE_1.name())).setHorizontalAlignment(HorizontalAlignment.RIGHT);
		final ComponentBuilder<?, ?> title = Components.text("FATURE UJI").setStyle(Styles.style().bold().setFontSize(30).setUnderline(true)).setHorizontalAlignment(HorizontalAlignment.CENTER);
		
		StyleBuilder textStyle = DynamicReports.stl.style(Templates.columnStyle)  
        .setBorder(DynamicReports.stl.pen1Point()).setFontSize(8);
		
		report.title(
				Components.verticalList(
						Components.horizontalList(cmp.verticalList(logo,title2),title1)),
						Components.line(),
						title);
		
		report.setPageMargin(DynamicReports.margin(4))
		 .setColumnStyle(textStyle)
		  .columns(
				  DynamicReports.col.column("KODI",       "id",      DynamicReports.type.integerType()).setFixedWidth(30),
				  DynamicReports.col.column("EMRI",   "emri",  DynamicReports.type.stringType()).setFixedWidth(120),
				  DynamicReports.col.column("MBIEMRI", "mbiemri", DynamicReports.type.stringType()).setFixedWidth(120),
				  DynamicReports.col.column("ADRESA", "adresa", DynamicReports.type.stringType()).setFixedWidth(200),
				  DynamicReports.col.column("NR. F. PAPAGUAR", "faturaPapaguarNeTotal", DynamicReports.type.integerType()).setFixedWidth(80))
		  .setDataSource(debitorList);
		
		return report;
	}
	
	public static JasperReportBuilder buildFaturaReport(Fatura fatura){
		ShortDateType shortDateType = new  ShortDateType();
		

		final JasperReportBuilder report = DynamicReports.report();
		report.setTemplate(Templates.reportTemplate);
		
		final ComponentBuilder<?, ?> logo = cmp.image(Templates.class.getResource("logo.jpg")).setFixedDimension(200, 80);
		final ComponentBuilder<?, ?> title2 = cmp.text(FaturaUKApplication.PARAMS.get(ParamsEnum.FATURA_REPORT_TITLE_2.name()));
		final ComponentBuilder<?, ?> title1 = cmp.text(FaturaUKApplication.PARAMS.get(ParamsEnum.FATURA_REPORT_TITLE_1.name())).setHorizontalAlignment(HorizontalAlignment.RIGHT);
		final ComponentBuilder<?, ?> title = Components.text("FATURE UJI").setStyle(Styles.style().bold().setFontSize(30).setUnderline(true)).setHorizontalAlignment(HorizontalAlignment.CENTER);
		final ComponentBuilder<?, ?> faturaReportKujtese = Components.text(FaturaUKApplication.PARAMS.get(ParamsEnum.FATURA_REPORT_KUJTESE.name())).setFixedWidth(147).setStyle(Styles.style().setPadding(3).setBorder(Styles.pen().setLineColor(Color.GRAY).setLineWidth(0.05f)).bold().setFontSize(8)).setHorizontalAlignment(HorizontalAlignment.RIGHT);
		
		final FieldBuilder<Integer> id = field("id",Integer.class);
		final FieldBuilder<String> emri = field("kontrata.emri",String.class);
		final FieldBuilder<String> mbiemri = field("kontrata.mbiemri",String.class);
		final FieldBuilder<String> adresa = field("kontrata.adresa", String.class);
		final FieldBuilder<String> perdorimi = field("kontrata.perdorimi.tag", String.class);
		
		final FieldBuilder<Date> dataLeximiAktual = field("dataLeximAktual", shortDateType);
		
		final ComponentBuilder<?, ?> emriMbiemriText = cmp.horizontalList(cmp.text(emri), cmp.text(" "), cmp.text(mbiemri)).setStyle(Styles.style().setBold(true).setFontSize(18));
		final ComponentBuilder<?, ?> adresaText = Components.text(adresa).setFixedWidth(180);
		final ComponentBuilder<?, ?> dataLeximiAktualText = Components.text(dataLeximiAktual).setStyle(Styles.style().setFontSize(14).setBold(true)).setHorizontalAlignment(HorizontalAlignment.RIGHT).setFixedWidth(408);
		
		

		final ComponentBuilder<?, ?> klienti = Components.verticalList(emriMbiemriText, adresaText);
		
		final HorizontalListBuilder faturaData = Components.horizontalList();
		
		addAttribute(faturaData, "Nr. i fatures", id);
		addAttribute(faturaData, "Data e fatures", dataLeximiAktual);
		addAttribute(faturaData, "Perdorimi", perdorimi);
		
		final ComponentBuilder<?, ?> comp1 = Components.verticalList(dataLeximiAktualText, Components.horizontalList(klienti, faturaData),cmp.subreport(createSubreport(fatura)));
		
		final ComponentBuilder<?, ?> comp2 = Components.horizontalList(comp1, faturaReportKujtese);
		
		report.title(
				Components.verticalList(
						Components.horizontalList(cmp.verticalList(logo,title2),title1)),
						Components.line(),
						title,
						comp2);
		
		List<Fatura> fL = new ArrayList<Fatura>();
		fL.add(fatura);
		report.setDataSource(fL);

		return report;
		
		
	}
	
	
	private static JRDataSource createSubreportDataSource(Fatura fatura) {
		DRDataSource dataSource = new DRDataSource("KODI", "PERSHKRIMI", "NJESIA", "SASIA", "CMIMI", "TVSH", "VLERA");
		List<Tarifa> tarifaList = fatura.getTarifaCollection();
		Double harxhimi = fatura.getLeximiAktual()-fatura.getLeximiKaluar();
		for (Tarifa tarifa : tarifaList) {
			double tvsh = 0;
			if (tarifa.isAplikoTVSH()){
				tvsh = (harxhimi * tarifa.getCmimi())* 20/100;
			}
			
			dataSource.add(tarifa.getKodi(), tarifa.getPershkrimi(), tarifa.getNjesia(), harxhimi , tarifa.getCmimi(),tvsh,tvsh + harxhimi * tarifa.getCmimi());
		}
		return dataSource;
	}
	
	
	
	
	
	private static JasperReportBuilder createSubreport(Fatura fatura) {
		
		
		StyleBuilder textStyle = DynamicReports.stl.style(Templates.columnStyle)  
        .setBorder(DynamicReports.stl.pen1Point()).setFontSize(8);
		
		JasperReportBuilder report = DynamicReports.report();
		report
		  .setTemplate(Templates.reportTemplate)
		  .setPageMargin(DynamicReports.margin(4))
		 .setColumnStyle(textStyle)
		  .columns(
				  DynamicReports.col.column("KODI",       "KODI",      DynamicReports.type.stringType()).setFixedWidth(30),
				  DynamicReports.col.column("PERSHKRIMI",   "PERSHKRIMI",  DynamicReports.type.stringType()),
				  DynamicReports.col.column("NJESIA", "NJESIA", DynamicReports.type.stringType()).setFixedWidth(20),
				  DynamicReports.col.column("SASIA", "SASIA", DynamicReports.type.doubleType()),
				  DynamicReports.col.column("CMIMI", "CMIMI", DynamicReports.type.doubleType()),
				  DynamicReports.col.column("TVSH(20%)", "TVSH", DynamicReports.type.doubleType()).setFixedWidth(30),
				  DynamicReports.col.column("VLERA", "VLERA", DynamicReports.type.doubleType()))
		  .setDataSource(createSubreportDataSource(fatura));
		
		return report;
	}
	


	public static void build(VerticalLayout vl, IFaturaBean faturaBean) throws IOException, DRException, Exception {
  
		Date start = new Date();
		System.out.println(start.getTime());
		InputStream is = Reports.class.getResourceAsStream("fatura-template.jrxml");	
		Date after1 = new Date();  
	    System.out.println("-------------");
	    System.out.println(after1.getTime() - start.getTime());
	    
	    final JasperReportBuilder report = DynamicReports.report();
	    Date after2 = new Date();  
	    System.out.println("-------------");
	    System.out.println(after2.getTime() - after1.getTime());
	    
	    
	    report.setTemplate(Templates.reportTemplate);
	    Date after3 = new Date();  
	    System.out.println("-------------");
	    System.out.println(after3.getTime() - after2.getTime());
	   
	    report.addColumn(Columns.column("Emri",       "kontrata.emri",      DataTypes.stringType()));
		report.addColumn(Columns.column("Mbiemri",   "kontrata.mbiemri",  DataTypes.stringType()));
		report.addColumn(Columns.column("Adresa", "kontrata.adresa", DataTypes.stringType()));
		report.addTitle(Components.text("Getting started"));
		report.addPageFooter(Components.pageXofY());
	    
	   // report.setDataSource( faturaBean.queryFatura());
	   
	    Date after4 = new Date();  
	    System.out.println("-------------");
	    System.out.println(after4.getTime() - after3.getTime());
	   
	    
	    StreamResource.StreamSource resstream = new FilePDF(report);
	    Date after5 = new Date();  
	      
	    System.out.println("-------------");
	    System.out.println(after5.getTime() - after4.getTime());
	    StreamResource ress = new StreamResource(resstream, "abc.pdf", vl.getApplication());
    
	    Date after = new Date();  
	    
	    System.out.println("-------------");
	    System.out.println(after.getTime() - after5.getTime());
	    
	    //
	    ress.setMIMEType("application/pdf");
	    ress.setCacheTime(1);
	    
	    //
	    Embedded c = new Embedded("Title", ress);
	    c.setSource(ress);
	    c.setMimeType("application/pdf");
	    c.setType(Embedded.TYPE_BROWSER);
	    c.setSizeFull();
	    c.setHeight("800px");
	    c.setParameter("Content-Disposition", "attachment; filename=" + ress.getFilename());
	    
	  
	    vl.addComponent(c);
	    Date now = new Date();
	    System.out.println("Koha ne ms");
	    System.out.println(now.getTime() - after.getTime());
	}
	    
	    

	
}
